<?php
namespace app\admin\controller;

use app\admin\controller\Base;
use app\admin\model\Fansrepetition;
use app\admin\model\Fodderimg;
use app\admin\model\Fodderimglist;
use app\admin\model\Fodderlink;
use app\common\model\admin\AdminModule;
use app\wechat\controller\account\Prowechat;
use app\wechat\controller\Index;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use think\Db;
use think\Request;
use think\facade\Session;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\facade\Env;
use think\Validate;
use think\facade\Cache;
use app\admin\model\Authorizer;

class Adminindex extends Base
{
    public function _initialize()
    {
        parent::_initialize();
    }
    public function adminindex()
    {
        $this->checklogin();
        $adminUser = Session::get('adminUser');

//        if($adminUser['username'] != 'nanxun'){
//            $role = $adminUser['roleid'];
//            $map_one = '';
//            $map_two = '';
//            $rulelist = Db::table('nx_admin_role')->where('id','in',$role)->field('rule')->select();
//            foreach ($rulelist as $k=>$v){
//                $modulea = Db::table('nx_admin_rule')->where('id','in',$v['rule'] )->field('modulea_one,modulea_two')->select();
//                foreach ($modulea as $key=>$val){
//                    $map_one = $map_one.','.$val['modulea_one'];
//                    $map_two = $map_two.','.$val['modulea_two'];
//                }
//            }
//            $map_one  =ltrim($map_one,',');
//            $map_two  =ltrim($map_two,',');
//            $olist = Db::table('nx_admin_modulea')->where('id','in',$map_one)
//                ->where('delstatus','1')->order('sort','asc')->select();
//            $tlist = Db::table('nx_admin_modulea')->where('id','in',$map_two)
//                ->where('delstatus','1')->order('sort','asc')->select();
//        }
//        else{
//            $firstMenuList = AdminModule::where('level', 1)->order('sort', 'asc')->select();
//            $secondMenuList = AdminModule::where('level', 2)->order('sort', 'asc')->select();
//        }

        $firstMenuList = AdminModule::where('level', 1)->order('sort', 'asc')->select();
        $secondMenuList = AdminModule::where('level', 2)->order('sort', 'asc')->select();

        $time = date('Y年m月d日',time());
        $this->assign('userinfo',$adminUser);
        $this->assign('time',$time);
        $this->assign('tlist',$secondMenuList);
        $this->assign('olist',$firstMenuList);
        return $this->fetch('adminindex/adminindex');
    }
    //修改资料
    public function editInfo()
    {
        $data= Session::get('adminuser.userid');
        $list = Db::table('nx_admin_user')->where('id',$data)->find();
        $this->assign('list',$list);
        return $this->fetch('adminindex/editInfo');
    }
    public function doEditInfo()
    {
        $id       = $this->request->post('id');
        $name     = $this->request->post('name');
        $loginid  = $this->request->post('loginid');
        $pwd      = $this->request->post('pwd');
        $data = [
            'username'   => $name,
            'loginid'    => $loginid,
            'password'        => md5($pwd),
            'updatetime' => date('Y-m-d H:i:s',time())
        ];
        $res = Db::name('nx_admin_user')->where('id',$id)->update($data);
        if($res){
            Session::delete('adminuser');
            return $this->api_resp_success('','',$res);
        }
    }
    /**
     * 公众号管理--公众号列表
     * 导入公众号信息
     **/
    public function uploadTencent()
    {
        $file = $this->request->file('file');
        $rootpath = Env::get('root_path');
        $info = $file->move($rootpath .'public/static/uploads');
        if ($info) {
            $files = $rootpath.'public/static/uploads/'.$info->getSaveName();
            // 成功上传后 返回上传信息
            $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
            $PHPExcel      = $reader->load($files); // 载入excel文件
            $sheet         = $PHPExcel->getSheet(0); // 读取第一個工作表
            $highestRow    = $sheet->getHighestRow(); // 取得总行数
            $highestColumm = $sheet->getHighestColumn(); // 取得总列数
            $data          = [];
            for ($row = 2; $row <= $highestRow; $row++)
            {
                for ($column = 'A'; $column <= $highestColumm; $column++) //列数是以A列开始
                {
                    if (empty($sheet->getCell($column . $row)->getValue()) == false) {
                        $str = $sheet->getCell($column . $row)->getValue();
                        $num = $row-2;
                        if($column == 'A'){
                            $data[$num]['ghid'] = $str;
                        }else if($column == 'B'){
                            $data[$num]['category'] = $str;
                        }else if($column == 'C'){
                            $data[$num]['category2'] = $str;
                        }elseif($column == 'D'){
                            $data[$num]['password'] = $str;
                        }elseif($column == 'E'){
                            $data[$num]['scan_phone'] = $str;
                        }
                    }
                }
            }
            if($data != ''){
                foreach($data as $k=>$v){
                    $udata = [
                        'category'=>$v['category'],
                        'category2'=>$v['category2'],
                        'password'=>$v['password'],
                        'scan_phone'=>$v['scan_phone']
                    ];
                    Db::name('nx_authorizer')->where('ghid',$v['ghid'])->update($udata);
                }
            }else{
                return json(array('code' => 404, 'msg' => '请导入有数据的表格'));
            }
            return json(array('code' => 0, 'msg' => '导入成功'));
        } else {
            // 上传失败返回错误信息
            return json(array('state' => 0, 'errmsg' => '上传失败'));
        }
    }
    /**
     * 复粉账号管理
     * 导入账号数据
     **/
    public function uploadAccount()
    {
        $file = $this->request->file('file');
        $rootpath = Env::get('root_path');
        $info = $file->move($rootpath .'public/static/uploads');
        if ($info) {
            $files = $rootpath.'public/static/uploads/'.$info->getSaveName();
            // 成功上传后 返回上传信息
            $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
            $PHPExcel      = $reader->load($files); // 载入excel文件
            $sheet         = $PHPExcel->getSheet(0); // 读取第一個工作表
            $highestRow    = $sheet->getHighestRow(); // 取得总行数
            $highestColumm = $sheet->getHighestColumn(); // 取得总列数
            $data          = [];
            for ($row = 2; $row <= $highestRow; $row++)
            {
                for ($column = 'A'; $column <= $highestColumm; $column++) //列数是以A列开始
                {
                    if (empty($sheet->getCell($column . $row)->getValue()) == false) {
                        $str = $sheet->getCell($column . $row)->getValue();
                        $num = $row-2;
                        if($column == 'A'){
                            $data[$num]['gh_id'] = $str;
                        }else if($column == 'B'){
                            $data[$num]['accountpool'] = $str;
                        }else if($column == 'C'){
                            $data[$num]['limit_min'] = $str;
                        }elseif($column == 'D') {
                            $data[$num]['limit_hour'] = $str;
                        }elseif($column == 'E') {
                            $data[$num]['limit_day'] = $str;
                        }elseif($column == 'F'){
                            $data[$num]['link_img_num'] = $str;
                        }
                    }
                }
            }
            if($data != ''){
                foreach($data as $k=>$v){
                    $name = Authorizer::where('ghid',$v['gh_id'])->value('name');
                    $category = Db::table('nx_replyfans_accountpool')->where('id',$v['accountpool'])->find();
                    if($name == false){
                        $name = '';
                    }else{
                        $udata = [
                            'name'            => $name,
                            'gh_id'           => $v['gh_id'],
                            'accountpool'     => $v['accountpool'],
                            'category_sum'    => $category['category_sum'],                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  
                            'category_child'  => $category['category_child'],
                            'link_img_num'    => $v['link_img_num'],
                            'limit_min'       => $v['limit_min'],
                            'limit_hour'      => $v['limit_hour'],
                            'limit_day'       => $v['limit_day'],
                            'status'          => 1,
                            'createtime'      => date('Y-m-d H:i:s',time())
                        ];
                        $result = Db::name('nx_replyfans_account')->insert($udata);
                        if($result){
                            $prowechat = new Prowechat();
                            //获取账号池下图片素材
                            $fodderimg = Fodderimg::where(['accountpool'=>$v['accountpool'],'delstaus'=>1])->select();
                            foreach ($fodderimg as $key=>$val){
                                //获取图片素材下图片链接的集合
                                $imglist = Fodderimglist::where(['delstatus'=>1,'fodderid'=>$val['id']])->select();
                                foreach ($imglist as $ke=>$value){
                                    //上传图片素材至微信获取图片链接
                                    $jsonlink = $prowechat->addOtherMaterial($v['ghid'],$value['imgurl']);
                                    $link = json_decode($jsonlink,true);
                                    $ldata = [
                                        'ghid'        => $v['gh_id'],
                                        'name'        => $name,
                                        'fodderlink'  => $link['url'],
                                        'status'      => 1,
                                        'createtime'  => date('Y-m-d H:i:s',time())
                                    ];
                                    Fodderlink::insert($ldata);
                                }
                            }
                        }
                    }
                }
            }else{
                return json(array('code' => 404, 'msg' => '请导入有数据的表格'));
            }
            return json(array('code' => 0, 'msg' => '导入成功'));
        } else {
            // 上传失败返回错误信息
            return json(array('state' => 0, 'errmsg' => '上传失败'));
        }
    }
    /**
     * 粉丝查重
     * 导出对比好的数据
     *
     **/
    public function downFansExcel()
    {
        $rows = Db::table('nx_fans_repetition')->where('delstatus',1)->order('repetrate asc')->select();
        $spreadsheet = new Spreadsheet();
        $worksheet = $spreadsheet->getActiveSheet();
        //设置工作表标题名称
        $worksheet->setTitle('粉丝查重数据对比信息表');
        //设置单元格内容
        $worksheet->setCellValueByColumnAndRow(1, 1, '原始ID1');
        $worksheet->setCellValueByColumnAndRow(2, 1, '公众号1');
        $worksheet->setCellValueByColumnAndRow(3, 1, '公众号1粉丝数量');
        $worksheet->setCellValueByColumnAndRow(4, 1, '原始ID2');
        $worksheet->setCellValueByColumnAndRow(5, 1, '公众号2');
        $worksheet->setCellValueByColumnAndRow(6, 1, '公众号2粉丝数量');
        $worksheet->setCellValueByColumnAndRow(7, 1, '粉丝重复数量');
        $worksheet->setCellValueByColumnAndRow(8, 1, '重复百分比');
        $worksheet->setCellValueByColumnAndRow(9, 1, '创建时间');
        $worksheet->setCellValueByColumnAndRow(10, 1, '更新时间');
        $worksheet->setCellValueByColumnAndRow(11, 1, '执行状态');
        $worksheet->setCellValueByColumnAndRow(12, 1, '执行失败原因');
        $j = 0;
        $num = count($rows);
        for ($i=0; $i < $num; $i++) {
            $j = $i + 2; //从表格第2行开始
            $worksheet->setCellValueByColumnAndRow(1, $j, $rows[$i]['ghid_1']);
            $worksheet->setCellValueByColumnAndRow(2, $j, $rows[$i]['name_1']);
            $worksheet->setCellValueByColumnAndRow(3, $j, $rows[$i]['fanstotal1']);
            $worksheet->setCellValueByColumnAndRow(4, $j, $rows[$i]['ghid_2']);
            $worksheet->setCellValueByColumnAndRow(5, $j, $rows[$i]['name_2']);
            $worksheet->setCellValueByColumnAndRow(6, $j, $rows[$i]['fanstotal2']);
            $worksheet->setCellValueByColumnAndRow(7, $j, $rows[$i]['repet_fans_total']);
            $worksheet->setCellValueByColumnAndRow(8, $j, $rows[$i]['repetrate']);
            $worksheet->setCellValueByColumnAndRow(9, $j, $rows[$i]['createtime']);
            $worksheet->setCellValueByColumnAndRow(10, $j, $rows[$i]['updatetime']);
            $worksheet->setCellValueByColumnAndRow(11, $j, $rows[$i]['status']);
            $worksheet->setCellValueByColumnAndRow(12, $j, $rows[$i]['errormsg']);
        }
        $filename = '粉丝查重数据对比信息表.xlsx';
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$filename.'"');
        header('Cache-Control: max-age=0');
        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
    }
    /**
     * 粉丝查重功能
     * 导入ghid进行查重列表
     **/
    public function uploadGhid()
    {
        $file = $this->request->file('file');
        $rootpath = Env::get('root_path');
        $info = $file->move($rootpath .'public/static/uploads');
        if ($info) {
            $files = $rootpath.'public/static/uploads/'.$info->getSaveName();
            // 成功上传后 返回上传信息
            $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
            $PHPExcel      = $reader->load($files); // 载入excel文件
            $sheet         = $PHPExcel->getSheet(0); // 读取第一個工作表
            $highestRow    = $sheet->getHighestRow(); // 取得总行数
            $highestColumm = $sheet->getHighestColumn(); // 取得总列数
            $data          = [];
            $data2         = [];
            for ($row = 2; $row <= $highestRow; $row++)
            {
                for ($column = 'A'; $column <= $highestColumm; $column++) //列数是以A列开始
                {
                    if (empty($sheet->getCell($column . $row)->getValue()) == false) {
                        $str = $sheet->getCell($column . $row)->getValue();
                        $num = $row-2;
                        if($column == 'A'){
                            $data[$num] = $str;
                        }
                        if($column == 'B'){
                            $data2[$num] = $str;
                        }
                    }
                }
            }
            if($data != '' && $data2 !=''){
                foreach($data as $k=>$v){
                    $name1 = Authorizer::where('ghid',$v)->value('name');
                    if ($name1) {
                        foreach ($data2 as $key=>$val){
                            if($v != $val){
                                $strs = $v.','.$val;
                                $repet = Fansrepetition::where('ghid_1','in',$strs)
                                    ->where('ghid_2','in',$strs)
                                    ->where('delstatus',1)
                                    ->find();
                                if($repet == ''){
                                    $name2 = Authorizer::where('ghid',$val)->value('name');
                                    if ($name2) {
                                        $udata = [
                                            'ghid_1'=>$v,
                                            'ghid_2'=>$val,
                                            'name_1'=>$name1,
                                            'name_2'=>$name2,
                                            'createtime'=>date('Y-m-d H:i:s',time()),
                                        ];
                                        Db::name('nx_fans_repetition')->insert($udata);
                                    }
                                }
                            }
                        }
                    }
                }
            }else{
                return json(array('code' => 404, 'msg' => '请导入有数据的表格'));
            }
            return json(array('code' => 0, 'msg' => '导入成功'));
        } else {
            // 上传失败返回错误信息
            return json(array('code' => 0, 'errmsg' => '上传失败'));
        }
    }
}
